const router = require("express")();
const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;

function buildSitemap() {
    if (sitemapCache) return sitemapCache;
    const baseUrl = 'http://dx.mapland.cn:48081';
    const idFinder = /<.*id=(.*?)(>| .*>)/g;
    const badIdFinder = /\$\{.*?\}/
    //寻找所有内容
    let urls = {};
    let dir = './public';
    let files = fs.readdirSync(dir);
    for (let x in files)
        if ((x = `${dir}/${files[x]}`).endsWith('.html')) {
            let lastmod = fs.statSync(x).mtime.toISOString();

            urls[x.substring(1)] = [1.0, lastmod];

            let data = fs.readFileSync(x, 'utf-8');
            let res;
            while (res = idFinder.exec(data)) {
                if (badIdFinder.test(res[1])) continue;
                let id = res[1].substring(1, res[1].length - 1);
                urls[`${x}#${id}`.substring(1)] = [0.8, lastmod];
            }
        }
    //构建xml
    let element = "";
    for (let path in urls) {
        if (path.length > 256) continue;
        element += `<url><loc>${baseUrl}/${path}</loc><priority>${urls[path][0]}</priority><lastmod>${urls[path][1]}</lastmod><changefreq>Daily</changefreq></url>`;
    }
    const xmlFrame = `<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="sitemap.xsl"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${element}</urlset>`
    sitemapCache = xmlFrame;
    setTimeout(() => sitemapCache = '', 1000 * 60);
    return xmlFrame;
}
let sitemapCache = '';
router.get('/sitemap.xml', function(req, res) {
    console.log('访问 /sitemap.xml: ', req.ip, req.ips);
    res.set('Content-Type', 'application/xml')
    res.status(200);
    res.send(buildSitemap());
});

let gitee_token = NCUTCAT.localProperty.webhook.gitee_token;
if (gitee_token === 'GITEE_TOKEN') gitee_token = `${Math.random()}${Math.random()}${Math.random()}`;
router.all('/gitee-webhook', function(req, res) {
    NCUTCAT.infoLog('WEBHOOK', '调用 gitee-webhook'.yellow);
    let token = req.headers['x-gitee-token'];
    if (token !== gitee_token) return res.end();
    let type = req.headers['x-gitee-event'].toLowerCase().trim();
    NCUTCAT.infoLog('WEBHOOK', '开始执行任务: '.yellow + type);
    switch (type) {
        case "push hook":
            {
                download(req.body.head_commit || {});
                break;
            }
    }
    res.end();
});

async function download(commit) {
    let success = true;
    NCUTCAT.infoLog("WEBHOOK", "开始拉取Git仓库");
    NCUTCAT.infoLog("GIT", `time: ${commit.timestamp}`);
    NCUTCAT.infoLog("GIT", commit.message);
    success = success && await new Promise(r => {
        exec("git pull", (err, out) => {
            if (err) NCUTCAT.error("无法拉取仓库", err);
            if (out) NCUTCAT.infoLog("GIT", out);
            r(!err);
        });
    });
    success && NCUTCAT.infoLog("WEBHOOK", "开始更新node module");
    success = success && await new Promise(r => {
        exec("npm install", (err, out) => {
            if (err) NCUTCAT.error("无法更新模块", err);
            if (out) NCUTCAT.infoLog("NPM", out);
            r(!err);
        });
    });
    if (success) {
        let hasCore = (arr) => {
            if (arr)
                for (let x in arr)
                    if (!arr[x].startsWith("public/")) return true;
        }
        let needRestart = !!(hasCore(commit.modified) || hasCore(commit.removed) || hasCore(commit.added));
        NCUTCAT.infoLog("重启", "需要重启: " + (needRestart ? "是".red : "否".green));
        if (needRestart) {
            let time = (1000 + Math.random() * 50000) | 0;
            NCUTCAT.warning(`重启 - 服务器将在 ${time/1000}秒 后重启.`);
            setTimeout(() => process.exit(5), time); //延时重启防止多节点同时重启}
        }
    }
}

//模块导出
module.exports = router;